package com.weirong.smartvault.backservice.util.table;

import com.weirong.smartvault.common.tools.constant.AuthorityConstant;
import com.weirong.smartvault.common.tools.spring.context.SpringContextUtil;
import com.weirong.smartvault.backservice.util.common.ListTool;
import com.weirong.smartvault.dao.AuthorityRepository;
import com.weirong.smartvault.backservice.entity_model.AuthorityModel;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: kfeb4
 * Date: 2017/12/30
 * Time: 18:12
 * 权限树生成
 */
public class AuthorityTree {
    static AuthorityRepository authorityRepository = SpringContextUtil.getBean(AuthorityRepository.class);
    static List<Tree<AuthorityModel>> buildTreeWithAllSon(Collection<AuthorityModel> m){
        Set<AuthorityModel> model = new HashSet<>(m);
        //1. 找到并添加所有节点的父节点
        for (AuthorityModel itm : m) {
            model.addAll(itm.getAllParents());
        }
        return buildTree(model);
    }
    public static List<Tree<AuthorityModel>> buildTree(Collection<AuthorityModel> model){
        //2. 按照层级划分
        Map<Object, List<AuthorityModel>> map = ListTool.divideByKey(model, AuthorityModel::getGrade);

        List<Tree<AuthorityModel>> roots = new ArrayList<>();
        Map<Integer, Tree<AuthorityModel>> nodes = new HashMap<>();
        //建树
        for (int i = 1; i < AuthorityConstant.lv + 1; i++) {
            if (map.containsKey(i)) {
                for (AuthorityModel authorityModel : map.get(i)) {
                    Tree<AuthorityModel> now = new Tree<>(authorityModel);
                    now.additionInf=authorityModel.getName()+","+authorityModel.getId();
                    if (i == 1)
                        roots.add(now);
                    nodes.put(authorityModel.getId(), now);
                    Integer parentId = authorityModel.getParentId();
                    if (parentId != null)
                        nodes.get(parentId).addSon(now);
                }
            }
        }
        return roots;
    }
    public static List<Tree<AuthorityModel>> getAllInTree() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        return buildTree(ListTool.cast(authorityRepository.findAll(),AuthorityModel.class));
    }
}
